package com.woniu.user.controller;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.woniu.entity.Result;
import com.woniu.order.feign.CouponsSeckillFeignClient;
import com.woniu.order.pojo.Coupons;
import com.woniu.user.pojo.UserCoupons;
import com.woniu.user.service.IUserCouponsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 用户优惠卷中间表 前端控制器
 * </p>
 *
 * @author LiFangyu
 * @since 2023-02-15
 */
@Api(tags = "用户优惠券中间表")
@RestController
@RequestMapping("/user-coupons")
public class UserCouponsController {

    @Autowired
    private IUserCouponsService userCouponsService;


    @Autowired
    private CouponsSeckillFeignClient couponsSeckillFeignClient;

    @Autowired
    private RedisTemplate redisTemplate;


    @ApiOperation("根据用户id查询优惠券中间表")
    @GetMapping("/{id}")
    public Result<UserCoupons> userCouponsById(@PathVariable Long id){
        UserCoupons userCoupons = userCouponsService.getById(id);
        return Result.ok(userCoupons);
    }

    @ApiOperation("查询所有优惠券中间表")
    @GetMapping("/findAll")
    public Result<List<UserCoupons>> userCouponsFindAll(){
        List<UserCoupons> userCouponsList = userCouponsService.list();
        return Result.ok(userCouponsList);
    }

    @ApiOperation("新增优惠券")
    @PostMapping("/saveOrUpdate")
    public Result<UserCoupons> querySave(@RequestBody UserCoupons userCoupons){
        boolean save = userCouponsService.save(userCoupons);
        return Result.ok();
    }



    @ApiOperation("将优惠券数据存到redis")
    @GetMapping("/async")
    public Result asyncDbToRedis(){
        userCouponsService.asyncDbToRedis();
        return Result.ok();
    }

    @Async
    @ApiOperation("用户领取优惠券")
    @PostMapping("/seckill/{userId}/{couponsId}")
    //@Scheduled(fixedRate = 10000)
    public Result seckill(@PathVariable Integer userId,@PathVariable Integer couponsId) throws JsonProcessingException {


        //左存右取
        Object seckillOver1 = redisTemplate.opsForList().rightPop("secKillCouponsOver1");

        if(seckillOver1 == null ){
            Result.error("优惠券已经领完======");
            couponsSeckillFeignClient.updateById(couponsId);
            return Result.error("优惠券已经领完======");
        }


        UserCoupons userCoupons = new UserCoupons();
        userCoupons.setUserId(userId);
        userCoupons.setCouponsId(couponsId);
        userCoupons.setStatus("0");
        userCouponsService.save(userCoupons);
        return Result.ok("领取成功！！！！");
    }

}
